package com.yww.algorithm.sort;

import java.util.Arrays;

/**
 * @author yww
 * @description 归并排序 自顶向下（递归）
 * @since 2024/2/23 17:02
 */
public class MergeSortTopDown {
    public static void sort(int[] arr) {
        split(arr, 0, arr.length - 1, new int[arr.length]);
    }

    private static void split(int[] arr, int left, int right, int[] temp) {
        if (left >= right) { // 治
            return;
        }
        int m = (left + right) >>> 1;
        split(arr, left, m, temp); // 左分
        split(arr, m + 1, right, temp); // 右分
        merge(arr, left, m, m + 1, right, temp); // 合
        System.arraycopy(temp, left, arr, left, right - left + 1);
    }

    private static void merge(int[] arr, int i, int iEnd, int j, int jEnd, int[] temp) {
        int k = i;
        while (i <= iEnd && j <= jEnd) {
            if (arr[i] < arr[j]) {
                temp[k] = arr[i++];
            } else {
                temp[k] = arr[j++];
            }
            k++;
        }

        if (i <= iEnd) {
            System.arraycopy(arr, i, temp, k, iEnd - i + 1);
        }
        if (j <= jEnd) {
            System.arraycopy(arr, j, temp, k, jEnd - j + 1);
        }
    }

    public static void main(String[] args) {
        int[] a = {6, 5, 4, 3, 2, 1};
        System.out.println(Arrays.toString(a));
        sort(a);
        System.out.println(Arrays.toString(a));
    }


}
